Popular Searches
Popular Course Categories
Popular Courses

Understanding object-oriented programming concepts

Understanding object-oriented programming concepts

5 mins Object-Oriented Programming in Dart

Understanding Object-Oriented Programming Concepts in Dart

Object-Oriented Programming (OOP) is a programming approach in which applications are designed around classes and objects. Instead of keeping data and functions completely separate, OOP allows developers to combine related data and behavior into reusable structures.

Dart is an object-oriented programming language, and understanding OOP is essential for Flutter development. JustAcademy's Flutter curriculum includes Object-Oriented Programming in Dart, along with classes, objects, constructors, inheritance, polymorphism, and abstraction in its Dart Programming Fundamentals module. :contentReference[oaicite:0]{index=0}

Explore JustAcademy Flutter Training


1. What Is Object-Oriented Programming?

Object-Oriented Programming is a programming paradigm that organizes software around objects. An object contains data and behavior related to a particular entity.

For example, in a student management application, a student may have:

  • Name
  • Age
  • Email
  • Course
  • Marks

The student may also perform actions such as:

  • Display student information
  • Calculate results
  • Update information
  • Check attendance

OOP allows these properties and behaviors to be grouped together in a Student class.

class Student {
  String name;
  int age;

  Student(this.name, this.age);

  void displayInfo() {
    print("Name: $name");
    print("Age: $age");
  }
}

2. Why Is OOP Important?

OOP becomes especially useful as applications become larger and more complex. It provides a structured way to organize data, functionality, and relationships between different parts of an application.

Major Advantages

  • Reusability: Classes and methods can be reused in different parts of an application.
  • Organization: Related data and functionality can be grouped together.
  • Maintainability: Well-structured classes can make changes easier to manage.
  • Scalability: New functionality can be added through additional classes and relationships.
  • Encapsulation: Internal data can be protected and accessed through controlled interfaces.
  • Abstraction: Unnecessary implementation details can be hidden.
  • Polymorphism: Different objects can provide different implementations of common behavior.

3. Real-World Example of OOP

Consider a banking application.

A bank account can have:

  • Account number
  • Account holder name
  • Balance

It can perform actions such as:

  • Deposit money
  • Withdraw money
  • Check balance

These can be represented using a class:

class BankAccount {
  String accountHolder;
  double balance;

  BankAccount(this.accountHolder, this.balance);

  void deposit(double amount) {
    balance += amount;
  }

  void showBalance() {
    print("Balance: ₹$balance");
  }
}

4. Class

A class is a blueprint or template used to create objects. It defines the properties and behaviors that objects created from that class can have.

Basic Syntax

class ClassName {
  // properties

  // methods
}

Example

class Car {
  String brand = "Toyota";

  void drive() {
    print("The car is driving");
  }
}

The Car class describes what a car object can contain and what it can do.


5. Object

An object is an instance of a class. When an object is created, it gets access to the properties and methods defined by its class.

class Car {
  String brand = "Toyota";

  void drive() {
    print("The car is driving");
  }
}

void main() {
  Car car = Car();

  print(car.brand);
  car.drive();
}

Output:

Toyota
The car is driving

Class vs Object

Class Object
Blueprint or template Instance of a class
Defines structure Uses the defined structure
Example: Car Example: Car()

6. Properties

Properties are variables declared inside a class. They represent the data or characteristics of an object.

class Product {
  String name = "Laptop";
  double price = 55000;
  int quantity = 1;
}

Accessing properties through an object:

void main() {
  Product product = Product();

  print(product.name);
  print(product.price);
  print(product.quantity);
}

7. Methods

A method is a function defined inside a class. Methods represent the behavior or actions of an object.

class Calculator {
  int add(int a, int b) {
    return a + b;
  }

  int multiply(int a, int b) {
    return a * b;
  }
}

void main() {
  Calculator calculator = Calculator();

  print(calculator.add(10, 20));
  print(calculator.multiply(5, 4));
}

Output:

30
20

8. Constructors

A constructor is used when creating an object and is commonly used to initialize its properties.

class Student {
  String name;
  int age;

  Student(this.name, this.age);
}

void main() {
  Student student = Student("Aman", 21);

  print(student.name);
  print(student.age);
}

Here, the constructor receives the student's name and age when the object is created.


9. The this Keyword

The this keyword refers to the current object. It is commonly used when constructor parameters have the same names as class properties.

class Employee {
  String name;
  double salary;

  Employee(this.name, this.salary);
}

In this.name, this refers to the current Employee object.


10. Encapsulation

Encapsulation means combining data and methods within a class while controlling how internal data is accessed or modified.

Dart supports library-private identifiers using an underscore prefix.

class BankAccount {
  double _balance = 0;

  void deposit(double amount) {
    if (amount > 0) {
      _balance += amount;
    }
  }

  double getBalance() {
    return _balance;
  }
}

void main() {
  BankAccount account = BankAccount();

  account.deposit(5000);

  print(account.getBalance());
}

The balance is maintained internally and accessed through methods provided by the class.

Benefits of Encapsulation

  • Controls access to internal data.
  • Helps protect object state.
  • Allows validation before changing data.
  • Keeps implementation details inside the class.
  • Creates a cleaner public interface.

11. Getters

A getter allows a value to be accessed using property-like syntax while keeping the implementation inside the class.

class User {
  String name;

  User(this.name);

  String get displayName => name;
}

void main() {
  User user = User("Rahul");

  print(user.displayName);
}

12. Setters

A setter allows a value to be assigned through controlled logic.

class User {
  String _name = "";

  String get name => _name;

  set name(String value) {
    if (value.isNotEmpty) {
      _name = value;
    }
  }
}

void main() {
  User user = User();

  user.name = "Aman";

  print(user.name);
}

13. Inheritance

Inheritance allows one class to extend another class. The child class can reuse functionality from the parent class and can also add or override behavior.

class Animal {
  void eat() {
    print("Animal is eating");
  }
}

class Dog extends Animal {
  void bark() {
    print("Dog is barking");
  }
}

void main() {
  Dog dog = Dog();

  dog.eat();
  dog.bark();
}

Output:

Animal is eating
Dog is barking

The Dog class inherits the eat() method from Animal.


14. Method Overriding

A child class can provide its own implementation of a method inherited from a parent class. This is called method overriding.

class Animal {
  void sound() {
    print("Animal makes a sound");
  }
}

class Dog extends Animal {
  @override
  void sound() {
    print("Dog barks");
  }
}

void main() {
  Dog dog = Dog();

  dog.sound();
}

Output:

Dog barks

15. Polymorphism

Polymorphism means that a common type can represent different objects, while the actual object determines which implementation is executed.

class Animal {
  void sound() {
    print("Animal sound");
  }
}

class Dog extends Animal {
  @override
  void sound() {
    print("Dog barks");
  }
}

class Cat extends Animal {
  @override
  void sound() {
    print("Cat meows");
  }
}

void main() {
  Animal animal1 = Dog();
  Animal animal2 = Cat();

  animal1.sound();
  animal2.sound();
}

Output:

Dog barks
Cat meows

The variables are declared using the common Animal type, but each object provides its own implementation of sound().


16. Abstraction

Abstraction means exposing the essential behavior while hiding unnecessary implementation details.

Dart provides abstract classes for defining abstractions.

abstract class Shape {
  double calculateArea();
}

class Circle extends Shape {
  double radius;

  Circle(this.radius);

  @override
  double calculateArea() {
    return 3.14 * radius * radius;
  }
}

void main() {
  Circle circle = Circle(5);

  print(circle.calculateArea());
}

The abstract Shape class defines what a shape should provide, while Circle implements the actual calculation.


17. Interfaces

In Dart, every class implicitly defines an interface. A class can implement another class using the implements keyword.

class Animal {
  void sound() {
    print("Animal sound");
  }
}

class Dog implements Animal {
  @override
  void sound() {
    print("Dog barks");
  }
}

With implements, the implementing class provides its own implementation of the required members.


18. Composition

Composition means creating a class that contains an object of another class. It represents a "has-a" relationship.

class Engine {
  void start() {
    print("Engine started");
  }
}

class Car {
  Engine engine = Engine();

  void startCar() {
    engine.start();
    print("Car started");
  }
}

void main() {
  Car car = Car();

  car.startCar();
}

Here, a Car has an Engine.


19. Inheritance vs Composition

Inheritance Composition
Represents an "is-a" relationship Represents a "has-a" relationship
Uses extends Uses objects as properties
Child inherits from parent Class contains another object
Example: Dog is an Animal Example: Car has an Engine

20. Static Members

A static member belongs to the class rather than to a particular object.

class Calculator {
  static int add(int a, int b) {
    return a + b;
  }
}

void main() {
  print(Calculator.add(10, 20));
}

No Calculator object is required to call the static method.


21. Named Constructors

Dart supports named constructors, which allow different ways of creating an object.

class User {
  String name;

  User(this.name);

  User.guest() : name = "Guest";
}

void main() {
  User user1 = User("Rahul");
  User user2 = User.guest();

  print(user1.name);
  print(user2.name);
}

Output:

Rahul
Guest

22. Factory Constructors

A factory constructor provides control over object creation and can return an existing instance or another implementation when appropriate.

class User {
  String name;

  User._internal(this.name);

  factory User(String name) {
    return User._internal(name);
  }
}

void main() {
  User user = User("Aman");

  print(user.name);
}

23. Four Main Pillars of OOP

The four commonly discussed pillars of Object-Oriented Programming are:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction
Pillar Purpose Dart Example
Encapsulation Control access to data Private members, getters, setters
Inheritance Reuse and extend functionality extends
Polymorphism Allow different implementations @override
Abstraction Hide unnecessary implementation details abstract

24. Relationship Between OOP Concepts

Class
  |
  |-- Properties
  |
  |-- Methods
  |
  |-- Constructor
  |
  ↓
Object
  |
  |-- Encapsulation
  |
  |-- Inheritance
  |
  |-- Polymorphism
  |
  |-- Abstraction
  |
  ↓
Reusable Application Components

25. OOP Example: Student Management System

class Student {
  String name;
  int marks;

  Student(this.name, this.marks);

  String getResult() {
    if (marks >= 40) {
      return "Pass";
    }

    return "Fail";
  }

  void display() {
    print("Name: $name");
    print("Marks: $marks");
    print("Result: ${getResult()}");
  }
}

void main() {
  Student student = Student("Aman", 75);

  student.display();
}

Output:

Name: Aman
Marks: 75
Result: Pass

This example combines a class, object, properties, constructor, method, conditional logic, and a return value.


26. OOP Example: E-Commerce Product

class Product {
  String name;
  double price;

  Product(this.name, this.price);

  double getDiscountedPrice(double discount) {
    return price - (price * discount / 100);
  }

  void displayProduct() {
    print("Product: $name");
    print("Price: ₹$price");
  }
}

void main() {
  Product product = Product(
    "Laptop",
    55000,
  );

  product.displayProduct();

  double finalPrice =
      product.getDiscountedPrice(10);

  print("Final Price: ₹$finalPrice");
}

27. OOP Example: Different Types of Employees

abstract class Employee {
  String name;
  double salary;

  Employee(this.name, this.salary);

  double calculateBonus();

  void displayInfo() {
    print("Name: $name");
    print("Salary: ₹$salary");
  }
}

class Developer extends Employee {
  Developer(String name, double salary)
      : super(name, salary);

  @override
  double calculateBonus() {
    return salary * 0.10;
  }
}

class Manager extends Employee {
  Manager(String name, double salary)
      : super(name, salary);

  @override
  double calculateBonus() {
    return salary * 0.20;
  }
}

void main() {
  Employee developer =
      Developer("Rahul", 60000);

  Employee manager =
      Manager("Priya", 90000);

  developer.displayInfo();
  print("Bonus: ₹${developer.calculateBonus()}");

  print("");

  manager.displayInfo();
  print("Bonus: ₹${manager.calculateBonus()}");
}

This example demonstrates abstraction, inheritance, constructors, method overriding, and polymorphism.


28. OOP in Flutter

OOP concepts are fundamental to Flutter because Flutter development uses Dart and relies heavily on classes and objects. JustAcademy's curriculum places OOP within Dart Programming Fundamentals before moving into Flutter widgets and UI development. :contentReference[oaicite:1]{index=1}

OOP concepts appear in Flutter in areas such as:

  • Flutter widgets
  • Stateless widgets
  • Stateful widgets
  • Data model classes
  • Service classes
  • API response models
  • Repository classes
  • Application state classes
  • Custom reusable components

Example of a Flutter Class

class WelcomeScreen extends StatelessWidget {
  const WelcomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: Text("Welcome to Flutter"),
      ),
    );
  }
}

The example demonstrates a Dart class being used to define a reusable Flutter UI component.


29. Flutter Model Class Example

In a Flutter application, data received from an API or database can be represented using model classes.

class User {
  final int id;
  final String name;
  final String email;

  User({
    required this.id,
    required this.name,
    required this.email,
  });
}

void main() {
  User user = User(
    id: 1,
    name: "Rahul",
    email: "[email protected]",
  );

  print(user.name);
  print(user.email);
}

30. OOP and Code Reusability

One of the major benefits of OOP is the ability to create reusable classes.

class Calculator {
  int add(int a, int b) {
    return a + b;
  }

  int subtract(int a, int b) {
    return a - b;
  }
}

void main() {
  Calculator calculator = Calculator();

  print(calculator.add(10, 5));
  print(calculator.subtract(10, 5));
}

The same Calculator class can be used throughout an application wherever these operations are required.


31. OOP and Maintainability

OOP can help separate application responsibilities into meaningful classes. For example, a Flutter application might use separate classes for:

  • User data
  • Product data
  • API communication
  • Authentication
  • Database operations
  • Business logic
  • UI components

This separation can make a large application easier to understand and maintain.


32. Common OOP Mistakes

Mistake 1: Confusing Class and Object

class Car {
  String brand = "Toyota";
}

The above code defines a class. An object must be created to create an instance:

Car car = Car();

Mistake 2: Making Every Relationship an Inheritance Relationship

Inheritance should represent an appropriate parent-child relationship. For relationships where one object contains another, composition can be more suitable.

Mistake 3: Creating Very Large Classes

A class should ideally have a clear responsibility. Putting unrelated functionality into one class can make the code harder to understand and maintain.

Mistake 4: Exposing Internal Data Unnecessarily

When appropriate, use encapsulation and controlled methods or accessors rather than exposing internal implementation details.


33. Best Practices for OOP in Dart

  • Use meaningful class names.
  • Keep each class focused on a clear responsibility.
  • Initialize required data through constructors.
  • Use private members when internal implementation should be hidden.
  • Use getters and setters when controlled property access is useful.
  • Use inheritance when there is a genuine "is-a" relationship.
  • Use composition for appropriate "has-a" relationships.
  • Use abstraction to define common contracts.
  • Use polymorphism when multiple implementations share a common type.
  • Keep Flutter UI, models, services, and business logic appropriately organized.

34. Practice Exercises

  1. Create a Student class with name, age, and marks.
  2. Create a constructor for the Student class.
  3. Add a method to display student information.
  4. Create a BankAccount class with deposit and withdrawal methods.
  5. Create a Product class with name and price.
  6. Create three different product objects.
  7. Create an Animal parent class.
  8. Create Dog and Cat child classes.
  9. Override a method in both child classes.
  10. Create an abstract Shape class.
  11. Implement Circle and Rectangle classes.
  12. Create a Flutter user model class.
  13. Create a Flutter product model class.
  14. Create a reusable Flutter widget using a custom class.

35. Quick Revision Table

Concept Meaning Dart Keyword / Feature
Class Blueprint for creating objects class
Object Instance of a class ClassName()
Property Data belonging to a class/object Variables
Method Behavior defined inside a class Functions
Constructor Initializes an object Constructor syntax
Encapsulation Controls access to internal data Private members, getters, setters
Inheritance Extends functionality from another class extends
Polymorphism Different implementations through a common type @override
Abstraction Hides implementation details abstract
Interface Defines a contract for implementation implements
Composition Uses objects inside other objects Object properties

36. Key Takeaways

  • OOP organizes programs around classes and objects.
  • A class is a blueprint, while an object is an instance of that class.
  • Properties represent data, while methods represent behavior.
  • Constructors initialize objects.
  • Encapsulation helps control access to internal data.
  • Inheritance allows one class to extend another.
  • Polymorphism allows different objects to provide different implementations through a common type.
  • Abstraction hides unnecessary implementation details.
  • Composition allows a class to use objects from other classes.
  • OOP concepts are fundamental to understanding Dart and Flutter application development.

37. Learn Flutter with JustAcademy

JustAcademy's Flutter course includes Dart Programming Fundamentals with functions and parameters, Object-Oriented Programming in Dart, classes, objects, constructors, inheritance, polymorphism, and abstraction. The curriculum then progresses into Flutter widgets, UI development, navigation, state management, APIs, Firebase, testing, projects, and other application-development topics. :contentReference[oaicite:2]{index=2}

Visit JustAcademy Flutter Training

To explore the course through a demo: Register for JustAcademy Course Demo

whatsapp